package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.utils.JsonUtils;
import com.github.aloxc.plugin.restplus.utils.StringUtils;
import com.google.gson.JsonElement;

import javax.swing.*;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

import static com.github.aloxc.plugin.restplus.common.Consts.*;

public class TreeNodeMenuItemActionListener implements ActionListener {
    private int optType;
    private Object obj;
    private JTree tree;
    private Map jsonEleTreeMap;

    public TreeNodeMenuItemActionListener(Map jsonEleTreeMap, JTree tree, int optType, Object obj) {
        this.jsonEleTreeMap = jsonEleTreeMap;
        this.optType = optType;
        this.obj = obj;
        this.tree = tree;
    }

    /**
     * 复制节点路径.
     *
     * @param treePath
     * @return
     */
    public String copyTreeNodePath(TreePath treePath) {
        String str = "";
        String s = "";
        int len = treePath.getPathCount() - 1;
        for (int i = 0; i <= len; i++) {
            s = treePath.getPathComponent(i).toString();
            if (i > 0) {
                str += String.valueOf(DOT);
            }
            if (i == len) {
                str += pstr(s)[1];
            } else {
                str += s.substring(2);
            }
        }
        str = StringUtils.replace(str, String.valueOf(DOT) + "[", "[");
        str = StringUtils.substring(str, 5);
        return str;
    }

    /**
     * 复制相似路径节点键值对.
     *
     * @param treeNode
     * @return
     */
    public String copySimilarPathKeyValue(TreeNode treeNode) {
        String str = "";
        String key = pstr(treeNode.toString())[1];
        TreeNode node = treeNode.getParent();
        if (node == null) {
            return "";
        }
        node = node.getParent();
        if (node == null) {
            return "";
        }
        int count = node.getChildCount();
        int size = 0;
        for (int i = 0; i < count; i++) {
            TreeNode child = node.getChildAt(i);
            if (child == null) {
                continue;
            }
            size = child.getChildCount();
            for (int i2 = 0; i2 < size; i2++) {
                TreeNode tmp = child.getChildAt(i2);
                if (tmp == null) {
                    continue;
                }
                String[] arr = pstr(tmp.toString());
                if (key != null && key.equals(arr[1])) {
                    str += arr[2] + "\n";
                }
            }
        }
        return str;
    }
    public static int getIndex(String str) {
        int index = -1;
        if (str == null || str.length() == 0) {
            return index;
        }
        index = str.lastIndexOf("[");
        if (index >= 0) {
            try {
                index = Integer.parseInt(str.substring(index + 1, str.length() - 1));
            } catch (Exception ex) {
                index = -1;
            }
        }
        return index;
    }

    public static String getKey(String str) {
        int index = -1;
        if (str == null || str.length() == 0) {
            return str;
        }
        index = str.lastIndexOf("[");
        if (index >= 0) {
            return str.substring(0, index);
        }
        return str;

    }
    /**
     * 复制节点内容.
     *
     * @param path     节点路径
     * @param isFormat 是否带格式
     * @return
     */
    private String copyNodeContent(String path, boolean isFormat) {
        String str = "";
        String[] arr = StringUtils.split(path, String.valueOf(DOT));
        JsonElement obj = (JsonElement) jsonEleTreeMap.get(tree.hashCode());
        if (arr.length > 1) {
            for (int i = 1; i < arr.length; i++) {
                int index = getIndex(arr[i]);
                String key = getKey(arr[i]);
                if (obj.isJsonPrimitive()) {
                    break;
                }
                if (index == -1) {
                    obj = obj.getAsJsonObject().get(key);
                } else {
                    obj = obj.getAsJsonObject().getAsJsonArray(key).get(index);
                }
            }
        }
        if (obj != null && !obj.isJsonNull()) {
            str = JsonUtils.toJson(obj, isFormat);
        }
        return str;
    }
    public static String[] pstr(String str) {
        //类型,key,value
        String[] arr = new String[3];
        arr[0] = str.substring(0, 1);
        int i = str.indexOf(SPLIT);
        if (C_ARR.equals(arr[0])) {
            arr[1] = str.substring(2);
            arr[2] = ARRAY;
        } else if (C_OBJ.equals(arr[0])) {
            arr[1] = str.substring(2);
            arr[2] = OBJECT;
        } else if (C_STR.equals(arr[0])) {
            arr[1] = str.substring(2, i);
            arr[2] = str.substring(i + 4, str.length() - 1);
        } else {
            arr[1] = str.substring(2, i);
            arr[2] = str.substring(i + 3, str.length());
        }
        return arr;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (obj == null) {
            return;
        }
        StringSelection stringSelection = null;
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (optType == 4) {
            String path = copyTreeNodePath((TreePath) obj);
            path = StringUtils.replace(path, String.valueOf(DOT), ".");
            stringSelection = new StringSelection(path);
            clipboard.setContents(stringSelection, null);
            return;
        } else if (optType == 5) {
            stringSelection = new StringSelection(copySimilarPathKeyValue((TreeNode) obj));
            clipboard.setContents(stringSelection, null);
            return;
        } else if (optType == 6 || optType == 7) {
            String path = copyTreeNodePath((TreePath) obj);
            boolean isForamt = false;
            if (optType == 7) {
                isForamt = true;
            }
            String str = copyNodeContent(path, isForamt);
            stringSelection = new StringSelection(str);
            clipboard.setContents(stringSelection, null);
            return;
        } else {
            String str = obj.toString();
            String[] arr = pstr(str);
            if ("<null>".equals(arr[2])) {
                arr[2] = "null";
            }
            if (optType == 1 || optType == 2) {
                stringSelection = new StringSelection(arr[optType]);
            } else if (optType == 3) {
                stringSelection = new StringSelection(str.substring(2));
            } else if (optType == 8) {
                String temp = "\"" + arr[1] + "\",\"" + arr[2] + "\"";
                stringSelection = new StringSelection(temp);
            }
            clipboard.setContents(stringSelection, null);
        }
    }
}
